import {onMounted, ref} from "vue";

interface ReplaceFieldNames {
    value: string,
    label: string
}

export function useSearchSelect<T>(
    api: (...args: any) => Promise<T>,
    searchParam: any,
    replaceFieldNames: ReplaceFieldNames = {label: 'label', value: 'value'},
    onSelect: Function
) {
    const data = ref<any[]>([]);
    const value = ref();
    let timeout: any;
    let currentValue = '';
    function fetch(value:any, callback: any) {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }

        currentValue = value;
        function fake() {
            api(searchParam).then((d) => {
                if (currentValue === value) {
                    const result = d as Array<any>;
                    const data: any[] = [];
                    result.forEach((r: any) => {
                        data.push({
                            value: r[replaceFieldNames.value],
                            label: r[replaceFieldNames.label],
                        });
                    });
                    callback(data);
                }
            });
        }
        timeout = setTimeout(fake, 300);
    }

    const handleSearch = (val: string) => {
        searchParam[replaceFieldNames.label] = val;
        fetch(val, (d: any[]) => (data.value = d));
    };
    const handleChange = (val: string) => {
        value.value = val;
        if (onSelect){
            onSelect(val)
        }
        // fetch(val, (d: any[]) => (data.value = d));
    };

    return {
        handleSearch,
        handleChange,
        data,
        value
    }
}
